package com.example.doctorstation.POJOController;

import com.example.doctorstation.Config.MyResponse;
import com.example.doctorstation.POJOData.MyResponseEnum;
import com.example.doctorstation.POJOData.User;
import com.example.doctorstation.POJOMapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
public class UserController {
    //注入UserMapper 这里DEA可能会提示报错不用理会就行
    @Resource
    private UserMapper userMapper;

    //SSHConnection sshConnection;
    @PostMapping("/login")
    public MyResponse getUser(@RequestBody User user) {
        System.out.println(user);
        Subject userSubject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());

        try {
            userSubject.login(token);
            return MyResponse.success("用户登录成功");
        } catch (UnknownAccountException e) {
            return MyResponse.error(MyResponseEnum.ACCOUNT_NOT_EXIST.getMessage());
        } catch (DisabledAccountException e) {
            return MyResponse.error(MyResponseEnum.ACCOUNT_IS_DISABLED.getMessage());
        } catch (IncorrectCredentialsException e) {
            return MyResponse.error(MyResponseEnum.INCORRECT_CREDENTIALS.getMessage());
        } catch (Throwable e) {
            e.printStackTrace();
            return MyResponse.error(e.getMessage());
        }

    }

    @GetMapping("/role")
    @RequiresRoles("SYS")
    public String role() {
        Subject subject = SecurityUtils.getSubject();
        // subject.checkRole("SYS");

        return "测试SYS用户角色权限";
    }

    /*@PostMapping("/user")
    public MyResponse getUser(@RequestParam String userid,@RequestParam String password)// HashMap<String, String> map )
    {
        User user = userMapper.getUser(Integer.parseInt(userid), password);
        MyResponse resp = new MyResponse();
        if(user !=null)
        {
            resp.setCode(1);
            resp.setMsg("登陆成功");
            resp.setData(user);
        }
        else
        {
            resp.setCode(0);
            resp.setMsg("用户名或密码错误");
        }
        return resp;
    }*/

    @GetMapping("/user1")
    public MyResponse findAll() {
        try {
            return new MyResponse(userMapper.getAllUsers(), "", "");
        } catch (Throwable e) {
            e.printStackTrace(); // error connecting SSH server
            return new MyResponse();
        }
    }
}